<?php
/**
 * Created by PhpStorm.
 * 订单生成
 * User: caicm
 * Date: 2017/8/29
 * Time: 23:16
 */

namespace SDXApi\Controller;


use Think\Controller;

class OrderBasicsAddController extends Controller {
    protected $order_goods;

    //订单金额比率
    protected $order_money_rate = array(
        //线下
        '1' => array(
            'a' => 1,
            'b' => 8,
            'c' => 49,
            'd' => 23,
            'e' => 18,
            'f' => 1,
        ),
        //线上
        '2' => array(
            'a' => 21,
            'b' => 18,
            'c' => 39,
            'd' => 13,
            'e' => 8,
            'f' => 1,
        )
    );

    //随机商品分类
    protected $cat_rate = array(
        '1' => array(
            '154' => 2009,
            '700' => 773,
            '892' => 404,
            '880' => 1880,
            '257' => 1140,
            '317' => 1223,
            '341' => 1636,
            '473' => 532,
            '460' => 401,
            '461' => 1,
            '187' => 1,
        ),
        '2' => array(
            '154' => 2396,
            '700' => 511,
            '892' => 779,
            '880' => 1693,
            '257' => 649,
            '317' => 1142,
            '341' => 1697,
            '473' => 686,
            '460' => 388,
            '461' => 0,
            '187' => 59,
        )
    );

    /**
     * 添加每天比例数据
     */
    public function add_order_basics_rate(){
        $file = file('8.txt');
        foreach ($file as $v){
            $data = split(" +",$v);
            $res[] = array(
                'offline_num' => trim($data[1]),
                'online_num' => trim($data[3]),
                'num' => trim($data[5]),
                'offline_money' => trim($data[6]),
                'on_money' => trim($data[8]),
                'money' => trim($data[11]),
                'data' => '201706'.trim($data[0]),
            );
        }

        $test = M('order_basics_rate')->addAll($res);
        print_r($res);exit;
    }

    /**
     * 修正订单金额
     */
    public function update_order_data(){
        set_time_limit(0);
        $order_rate = M('order_basics_rate')->where(array('is_ok'=>2))->order('id asc')->find();
        M('order_basics_rate')->where(array('id' => $order_rate['id']))->save(array('is_ok'=>3));
        $begin = strtotime($order_rate['data']);
        $end = $begin + 86400;

        $where = "$begin < add_time and add_time < $end and order_type =1";
        $order_off =  M('order_basics1')->where($where)->sum('total_amount');

        $offline = $order_off-$order_rate['offline_money'];

        while  (true){
            if($offline){
                $order_list = M('order_basics1')->where($where)->order('total_amount desc')->select();

                foreach ($order_list as $k=>$v){
                    if($offline == 0){
                        break;
                    }
                    $goods = M('order_goods_basics')->field('goods_price*goods_num as totla,id,count(id) as num,goods_num')->where(array('order_id'=>$v['id']))->order('totla desc')->find();

                    if($goods['num'] > 1){

                        if($offline - $goods['totla'] < 0){
                            if($goods['goods_num'] == 1){
                                $dec_money =  $offline;
                                M('order_goods_basics')->where(array('id'=>$goods['id']))->setDec('goods_price', $offline);
                            }else{
                                continue;
                            }


                        }else{
                            $dec_money = $goods['totla'];
                            M('order_goods_basics')->where(array('id'=>$goods['id']))->delete();

                        }
                        $offline = $offline-$dec_money;
                        M('order_basics1')->where(array('id'=>$v['id']))->setDec('total_amount', $dec_money);

                    }
                }
            }
        }


        M('order_basics_rate')->where(array('id' => $order_rate['id']))->save(array('is_ok'=>4));
        header("location:index.php?s=/order_basics_add/update_order_data");
    }

    /**
     * 修正订单金额
     */
    public function update_order_data2(){
        set_time_limit(0);
        $order_rate = M('order_basics_rate')->where(array('is_ok'=>4))->order('id asc')->find();
        M('order_basics_rate')->where(array('id' => $order_rate['id']))->save(array('is_ok'=>5));
        $begin = strtotime($order_rate['data']);
        $end = $begin + 86400;

        $where = "$begin < add_time and add_time < $end and order_type =2";
        $order_off =  M('order_basics1')->where($where)->sum('total_amount');

        $offline = $order_off-$order_rate['offline_money'];

        while  (true){
            if($offline){
                $order_list = M('order_basics1')->where($where)->order('total_amount desc')->select();

                foreach ($order_list as $k=>$v){
                    if($offline == 0){
                        break;
                    }
                    $goods = M('order_goods_basics')->field('goods_price*goods_num as totla,id,count(id) as num,goods_num')->where(array('order_id'=>$v['id']))->order('totla desc')->find();

                    if($goods['num'] > 1){

                        if($offline - $goods['totla'] < 0){
                            if($goods['goods_num'] == 1){
                                $dec_money =  $offline;
                                M('order_goods_basics')->where(array('id'=>$goods['id']))->setDec('goods_price', $offline);
                            }else{
                                continue;
                            }


                        }else{
                            $dec_money = $v['totla'] - $goods['totla'];
                            M('order_goods_basics')->where(array('id'=>$goods['id']))->delete();

                        }
                        $offline = $offline-$dec_money;
                        M('order_basics1')->where(array('id'=>$v['id']))->setDec('total_amount', $dec_money);

                    }
                }
            }
        }


        M('order_basics_rate')->where(array('id' => $order_rate['id']))->save(array('is_ok'=>6));
        header("location:index.php?s=/order_basics_add/update_order_data");
    }


    /**
     * 添加数据到订单表
     */
    public function get_order_data(){
        set_time_limit(0);

        $order_rate = M('order_basics_rate')->where(array('is_ok'=>0))->order('id asc')->find();
        M('order_basics_rate')->where(array('id' => $order_rate['id']))->save(array('is_ok'=>1));

        $data = $this->get_rate_num($order_rate);
        $order_time = $this->get_order_time($order_rate);

        foreach ($data as $k=>$v) {
            $this->order_goods = array();

            $order_money = $this->get_order_money_rate($v);

            $order = array(
                'order_sn' => $order_time[$k]['order_sn'],
                'user_id' => mt_rand(1, 1840000),
                'add_time' => $order_time[$k]['add_time'],
                'pay_time' => $order_time[$k]['pay_time'],
                'order_type' => $v,
                'order_source' => mt_rand(1, 3),
                'total_amount' => 0
            );

            $order_id = M('order_basics1')->add($order);

            $goods = array();
            $total_amount = 0;
            $order_goods = $this->get_order_goods($v, $order_money);
            foreach ($order_goods as $key => $val) {
                $goods[$key] = array(
                    'order_id' => $order_id,
                    'goods_id' => $val['goods_id'],
                    'goods_sn' => $val['goods_sn'],
                    'goods_name' => $val['goods_name'],
                    'goods_num' => $val['goods_num'],
                    'goods_price' => $val['shop_price'],
                );
                $total_amount += $val['goods_num']*$val['shop_price'];
            }

            M('order_goods_basics')->addAll($goods);
            M('order_basics1')->where(array('id' => $order_id))->save(array('total_amount' => $total_amount));

        }
        M('order_basics_rate')->where(array('id' => $order_rate['id']))->save(array('is_ok'=>2));
        //header("location:index.php?s=/order_basics_add/get_order_data");


    }

    protected function get_order_time($order_rate){
        $begin = strtotime($order_rate['data']);
        $end = $begin + 86400;

        return M('order_basics')->where("$begin < add_time and add_time < $end")->limit($order_rate['num'])->select();

    }

    /**
     * 获取生成订单次数
     * @param $order_rate
     * @return array
     */
    protected function get_rate_num($order_rate){
        $data = array();
        for ($i=1; $i<=$order_rate['num']; $i++){
            if($i <= $order_rate['offline_num']){
                $data[] = 1;
            }else{
                $data[] = 2;
            }
        }
        shuffle($data);

        return $data;

    }

    protected $goods_id=0;

    /**
     * 获取订单商品数据
     * @param $store
     * @param $order_money
     * @param int $total_money
     * @return array
     */
    protected function get_order_goods($store, $order_money, $total_money=0){
        $cat_id = $this->get_rand_cat($store);

        $goods_info = $this->get_rand_goods($cat_id);

        $goods_info['goods_num'] = $this->get_goods_num();
        $goods_info['total_money'] = $goods_info['shop_price'] * $goods_info['goods_num'];


        $total = $goods_info['total_money']+$total_money;

        if($total > $order_money){
            $goods_info['goods_num'] = 1;
            $goods_info['total_money'] = $goods_info['shop_price'] * $goods_info['goods_num'];
            $total = $goods_info['total_money']+$total_money;
        }

        $this->order_goods[] = $goods_info;

        if($total < $order_money){
            $this->goods_id = ($this->goods_id==0 ? '' : ',').$goods_info['goods_id'];

            $this->get_order_goods($store, $order_money, $total);
        }

        return $this->order_goods;

    }


    /**
     * 获取随机商品信息
     * @param $cat_id
     * @return mixed
     */
    protected function get_rand_goods($cat_id){
        $cat_id_list = $this->get_cat_id($cat_id);

        $where = array(
            'cat_id' => array('in', $cat_id_list),
            'shop_price' => array('gt', 0)

        );
        if($this->goods_id){
            $where['goods_id'] = array('notin', $this->goods_id);
        }

        $count = M('goods')->where($where)->count();

        $rand_num = mt_rand(1,$count);
        $limit = $rand_num-1 . ',' . $rand_num;

        $goods_info = M('goods')
            ->field('goods_id,goods_name,goods_sn,shop_price')
            ->where($where)
            ->limit($limit)
            ->find();
        $goods_info['shop_price'] = number_format($goods_info['shop_price'] * 0.88, 1, '.', '');

        return $goods_info;

    }

    //获取当前一级分类id下的所有子分类id
    protected function get_cat_id($cat_id){

        $id_list[] = $cat_id;
        $res = M('Category')->where("parent_id={$cat_id}")->field('cat_id')->select();
        foreach ($res as $k){
            $res2 = array();
            $id_list[] = $k['cat_id'];
            $res2 = $res = M('Category')->where("parent_id={$k['cat_id']}")->field('cat_id')->select();
            foreach ($res2 as $kal){
                $id_list[] = $kal['cat_id'];
            }
        }

        return implode(',', $id_list);

    }

    /**
     * 获取商品随机数量
     * @return int
     */
    protected function get_goods_num(){
        return mt_rand(1, 7);
    }

    /**
     * 获取随机分类
     * @param $store
     * @return string
     */
    public function get_rand_cat($store){
        return $this->roll($this->cat_rate[$store]);
    }

    /**
     * 获取随机金额
     * @param $store
     * @return int
     */
    protected function get_order_money_rate($store){

        $date = array(
            'a' => array(5, 50),
            'b' => array(50, 100),
            'c' => array(100, 150),
            'd' => array(150, 200),
            'e' => array(200, 300),
            'f' => array(300, 1000),
        );

        $key = $this->roll($this->order_money_rate[$store]);
        $res = $date[$key];

        return mt_rand($res[0], $res[1]);

    }




    /**
     * 获取随机值
     * @param array $weight 权重
     * @return string key 键名
     */
    protected function roll($weight = array()) {
        $roll = rand ( 1, array_sum ( $weight ) );
        $_tmpW = 0;
        $rollnum = 0;
        foreach ( $weight as $k => $v ) {
            $min     = $_tmpW;
            $_tmpW += $v;
            $max     = $_tmpW;
            if ($roll > $min && $roll <= $max) {
                $rollnum = $k;
                break;
            }
        }
        return $rollnum;
    }
}